import path, { resolve } from 'path';
import fs from 'fs';
// import type { Plugin } from "vite"
// interface OptionVersion {
// 	version: number | string;
// }
// interface configObj extends Object {
// 	publicDir: string;
// }
const getCurrentVersion = () => {
  const vers = fs.readFileSync('.version.json');
  if (vers) {
    return JSON.parse(vers.toString('utf-8'));
  }
  return null;
};

const createNewVersion = (version) => {
  if (version) {
    const vers = version.split('.');

    const num = parseInt(vers.pop()) + 1;

    vers.push(num);

    return vers.join('.');
  }
};

const updateVersion = (newVersion, data) => {
  data.version = newVersion;

  const date = new Date();
  data.updateTime = [date.toLocaleDateString(), date.toLocaleTimeString()].join(
    ' '
  );

  const newVersionData = JSON.stringify(data);
  fs.writeFileSync('.version.json', newVersionData);
  // console.log(path.join();
  fs.writeFileSync(
    `${resolve(__dirname, '../../public/version')}.txt`,
    newVersionData
  );
  return data;
};
// const writeVersion = (
//   versionFileName: string,
//   content: string | NodeJS.ArrayBufferView
// ) => {
//   // 写入文件
//   fs.writeFile(versionFileName, content, (err) => {
//     if (err) throw err;
//   });
// };
export default () => {
  let config;
  // let config: configObj = {
  //   publicDir: ""
  // }
  return {
    name: 'version-update',
    configResolved(resolvedConfig) {
      // 存储最终解析的配置
      config = resolvedConfig;
    },
    buildStart() {
      // 生成版本信息文件路径
      // const file = config.publicDir + path.sep + 'version.json';
      // 这里使用编译时间作为版本信息
      const versionData = getCurrentVersion();
      let res;
      if (process.env.NODE_ENV === 'development') {
        res = versionData;
      } else {
        const newVersion = createNewVersion(versionData.version);
        // const newVersionData = updateVersion(newVersion, versionData)
        if (fs.existsSync(config.publicDir)) {
          // writeVersion(file, res);
          const newVersionData = updateVersion(newVersion, versionData);
          res = newVersionData;
        } else {
          fs.mkdir(config.publicDir, (err) => {
            if (err) throw err;
            // writeVersion(file, res);
            const newVersionData = updateVersion(newVersion, versionData);
            res = newVersionData;
          });
        }
        console.log(res, '版本');
      }
    },
    getCurrentVersion,
  };
};
